package com.yujn.springsecurityactual.controller;

import com.google.code.kaptcha.Producer;
import com.yujn.springsecurityactual.bean.Final;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @description: 图形验证码controller
 * @author: Yujn
 * @create: 2021-03-22 21:06
 **/
@RestController
public class CaptchaController {
    @Autowired
    private Producer producer;

    /**
     * 获取图形验证码
     * @param request
     * @param response
     * @return
     * @author yujn
     * @date 2021/3/23 10:49
     */
    @GetMapping("captcha/getImage")
    public void getCaptchar(HttpServletRequest request, HttpServletResponse response)throws IOException{
        // 设置响应类型
        response.setContentType("image/jpeg");
        // 创建验证码文本
        String capText = producer.createText();
        // 将验证码文本设置到session
        request.getSession().setAttribute(Final.CAPTCHA,capText);
        // 创建验证码图片
        BufferedImage bi = producer.createImage(capText);
        // 获取响应输出流
        ServletOutputStream out = response.getOutputStream();
        // 将图片验证码数据写到响应输出流
        ImageIO.write(bi,"jpg",out);
        // 推送并关闭响应输出流
        try {
            out.flush();
        } finally {
            out.close();
        }
    }
}
